package sample.stock;

import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;

import sample.stock.model.Stock;
import sample.stock.model.YahooStock;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class StockYahoo extends Activity {
	
	private Button next = null;
	private Button update = null;
	private TextView symbol = null;
	private TextView open = null;
	private TextView high = null;
	private TextView low = null;
	private TextView prevClose = null;
	private TextView volume = null;
	private TextView date = null;
	private TextView change = null;
	private TextView P_E = null;
	private TextView mktCap = null;
	private TextView percentChange = null;
	private TextView annRange = null;
	private TextView earns = null;
	private TextView name = null;
	private TextView last = null;
	
	private static final String SOAP_ACTION = "http://www.webserviceX.NET/GetQuote";
	private static final String NAMESPACE = "http://www.webserviceX.NET/";
	private static final String METHOD_NAME = "GetQuote";
	private static final String URL = "http://www.webservicex.net/stockquote.asmx";
	
	private ProgressDialog progressDialog;
	
    private AutoCompleteTextView mTicker;
            
	@SuppressWarnings("unchecked")
	@Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.stockyahoo);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        
        symbol = (TextView)findViewById(R.id.symbol);
        open = (TextView)findViewById(R.id.open);
        high = (TextView)findViewById(R.id.high);
        low = (TextView)findViewById(R.id.low);
        prevClose = (TextView)findViewById(R.id.prevClose);
        volume = (TextView)findViewById(R.id.volume);
        date = (TextView)findViewById(R.id.date);
        change = (TextView)findViewById(R.id.change);
        percentChange = (TextView)findViewById(R.id.percentChange);
        annRange = (TextView)findViewById(R.id.annRange);
        P_E = (TextView)findViewById(R.id.P_E);
        earns = (TextView)findViewById(R.id.earns);
        name = (TextView)findViewById(R.id.name);
        mktCap = (TextView)findViewById(R.id.mktCap);
        last = (TextView)findViewById(R.id.last);
        
        mTicker = (AutoCompleteTextView)findViewById(R.id.autoCompleteTicker);
        final ArrayAdapter adapterNASDAQ = ArrayAdapter.createFromResource(this, R.array.NASDAQ, R.layout.list_ticker);
        mTicker.setAdapter(adapterNASDAQ);
        
        next = (Button)findViewById(R.id.button1);
        next.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent chartView = new Intent(StockYahoo.this, AdvanceYChart.class);
				chartView.putExtra("symbol", mTicker.getText().toString());
				startActivity(chartView);
			}
		});
        
        update = (Button)findViewById(R.id.button3);
        update.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				progressDialog = new ProgressDialog(StockYahoo.this);
				progressDialog.setMessage("Loading...");
				new LoadStockTask(progressDialog).execute();
			}
		});
        
        Bundle extras = getIntent().getExtras();
        if(extras != null && extras.containsKey("symbol"))
        {
        	mTicker.setText(extras.getString("symbol"));
        	update.performClick();
        }
    }
    
    private class LoadStockTask  extends AsyncTask<Void, Void, Void> {
	  	  private ProgressDialog progress;
	  	  private YahooStock stock = null;
	  	  
	  	  public LoadStockTask(ProgressDialog progress) {
	  		    this.progress = progress;
	  		  }
	
	  		  public void onPreExecute() {
	  		    progress.show();
	  		  }
	
	  		  public void onPostExecute(Void unused) {
	  			  if(stock != null)
	  				DisplayStock(stock);
	  			  else
	  				  DisplayError();
	  			  if(progress.isShowing())
	  				  progress.dismiss();
	  		  }
	
			@SuppressWarnings("deprecation")
			@Override
	  		protected Void doInBackground(Void... arg0) {
				String symbol = mTicker.getText().toString();
	  				
	  			SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
	  			Request.addProperty("symbol", symbol); // replace by selected ticker in spinner
	  		        
	  			SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
	  			soapEnvelope.dotNet = true;
	  			soapEnvelope.setOutputSoapObject(Request);
	  		        
	  			AndroidHttpTransport aht = new AndroidHttpTransport(URL);
	  			try{
	  				aht.call(SOAP_ACTION, soapEnvelope);
	  				SoapPrimitive responseResult = (SoapPrimitive)soapEnvelope.getResponse();
	  				stock  = ParseSoapResponse_Stock(responseResult);
	  			}catch (SocketTimeoutException e){
	  				progress.dismiss();
	  			}
	  			catch(Exception e){
	  				e.printStackTrace();
	  			}
	  			return null;
	  		}
    }
  
  public YahooStock ParseSoapResponse_Stock(SoapPrimitive result)
  {
  		String temp = result.toString();
  	
    	YahooStock stock = new YahooStock();
    	stock.symbol = temp.substring(temp.indexOf("<Symbol>")+8, 
    			temp.indexOf("</Symbol>", temp.indexOf("<Symbol>")));
    	stock.last = temp.substring(temp.indexOf("<Last>")+6, 
    			temp.indexOf("</Last>", temp.indexOf("<Last>")));
    	stock.date = temp.substring(temp.indexOf("<Date>")+6, 
    			temp.indexOf("</Date>", temp.indexOf("<Date>")));
    	stock.time = temp.substring(temp.indexOf("<Time>")+6, 
    			temp.indexOf("</Time>", temp.indexOf("<Time>")));
    	stock.change = temp.substring(temp.indexOf("<Change>")+8, 
    			temp.indexOf("</Change>", temp.indexOf("<Change>")));
    	stock.open = temp.substring(temp.indexOf("<Open>")+6, 
    			temp.indexOf("</Open>", temp.indexOf("</Open>")));
    	stock.high = temp.substring(temp.indexOf("<High>")+6, 
    			temp.indexOf("</High>", temp.indexOf("<High>")));
    	stock.low = temp.substring(temp.indexOf("<Low>")+5, 
    			temp.indexOf("</Low>", temp.indexOf("<Low>")));
    	stock.volume = temp.substring(temp.indexOf("<Volume>")+8, 
    			temp.indexOf("</Volume>", temp.indexOf("<Volume>")));
    	stock.MktCap = temp.substring(temp.indexOf("<MktCap>")+8, 
    			temp.indexOf("</MktCap>", temp.indexOf("<MktCap>")));
    	stock.prevClose = temp.substring(temp.indexOf("<PreviousClose>")+15, 
    			temp.indexOf("</PreviousClose>", temp.indexOf("<PreviousClose>")));
    	stock.percentChange = temp.substring(temp.indexOf("<PercentageChange>")+19, 
    			temp.indexOf("</PercentageChange>", temp.indexOf("<PercentageChange>")));
    	stock.annRange = temp.substring(temp.indexOf("<AnnRange>")+10, 
    			temp.indexOf("</AnnRange>", temp.indexOf("<AnnRange>")));
    	stock.earns = temp.substring(temp.indexOf("<Earns>")+7, 
    			temp.indexOf("</Earns>", temp.indexOf("<Earns>")));
    	stock.P_E = temp.substring(temp.indexOf("<P-E>")+5, 
    			temp.indexOf("</P-E>", temp.indexOf("<P-E>")));
    	stock.name = temp.substring(temp.indexOf("<Name>")+6, 
    			temp.indexOf("</Name>", temp.indexOf("<Name>")));
  	
  	return stock;
  }
  
  public void DisplayError()
	{
		TextView errorTextView = (TextView) findViewById(R.id.errorMessage);
		errorTextView.setText("Service unreachable in a moment. Please try again later.");
		RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.rlServiceMessage);
		relativeLayout.setVisibility(View.VISIBLE);
	}
  
  public void DisplayStock(YahooStock s)
  {
	RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.rlServiceMessage);
	relativeLayout.setVisibility(View.GONE);
		
	symbol.setText(s.symbol);
  	last.setText(s.last);
  	date.setText(s.date + " " + s.time);
  	open.setText(s.open);
  	high.setText(s.high);
  	low.setText(s.low);
  	volume.setText(s.volume);
  	prevClose.setText(s.prevClose);
  	percentChange.setText(s.percentChange);
  	annRange.setText(s.annRange);
  	mktCap.setText(s.MktCap);
  	earns.setText(s.earns);
  	P_E.setText(s.prevClose);
  	name.setText(s.name);
  	change.setText(s.change);
  } 
}
